package com.myz.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        // 注入
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }
    /*
    * confirm方法无论是否成功,都会被回调
    * 成功时: 参数1是包含各种信息的对象, 参数2 true , 参数3 null
    * 失败时: 参数1----------------, 参数2 false, 参数3 失败的原因
    * */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cases) {
        String id = correlationData!=null?correlationData.getId():"";
        if (ack) {
            log.info("交换机成功收到id为{}的消息",id);
        } else{
            log.info("交换机还未收到id为{}的消息,原因:{}",id,cases);
        }
    }
    /*
    * 回退方法,该方法可以在当消息传递过程中不可达目的地时将消息返回给生产者
    * 只有当不可达目的地的时候，才进行回退
    * ReturnedMessage
        private final Message message;
        private final int replyCode;
        private final String replyText;
        private final String exchange;
        private final String routingKey;
    * */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("消息{},被交换机{}退回,原因:{},routingKey:{}",returnedMessage.getMessage(),
                returnedMessage.getReplyCode(),
                returnedMessage.getReplyText(),
                returnedMessage.getRoutingKey());
    }
}
